package com.albon.baseball;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


import com.albon.sportsalarm.R;
import com.albon.util.Logg;

public class BaseballParser {

	private final String TAG = "BaseballParser";
	private String baseball_host;
	private String baseball_link;
	private Context context;
	private Handler handler;
	private Source source;	
	private String year;
	private String month;
	private String league;
	private ProgressDialog pDialog = null;
	private ArrayList<HashMap<String, String>> data;
	private int world = 0;
	private String mYear;
	private String mMonth;
	private  String[] notification_time_array_name =  {};
	
	public BaseballParser(Context context, Handler handler, ArrayList<HashMap<String, String>> data, int world, String mYear, String mMonth, String league)
	{
		this.context = context;
		this.handler = handler;
		this.data = data;
		this.world = world;
		this.mYear = mYear;		
		this.mMonth = mMonth;
		this.league = league;
		notification_time_array_name = context.getResources().getStringArray(R.array.notification_time_array_name);
	}
	
	
	public void parser() {
		year = mYear;
		month = mMonth;
		
		
		baseball_host = "http://sports.media.daum.net";
		if(world==0){ // 해외 야구
			baseball_link = "/worldbaseball/mlb/schedule/main.daum?game_year=" 
						+ year
						+ "&game_month="
						+ month;
					
		}else{        // 국내 야구
			baseball_link = "/baseball/kbo/schedule/main.daum?game_year=" 
						+ year
						+ "&game_month="
						+ month;
			
		}
		//Logg.d(TAG, "soccer_link : "+soccer_link);
		try {
			process();
		} catch(IOException e){
			e.printStackTrace();
		}
	}

	public void progressStatus(int total) {
		pDialog.setProgress(total);
	}
	
	private void process() throws IOException {

		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				URL nURL;
				try {
					nURL = new URL(baseball_host + baseball_link);
					
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							pDialog = ProgressDialog.show(context, "", "로딩중");
							pDialog.setCancelable(true);
						}
					});
					
					data.clear();
					
					/***********************
					 * Jericho HTML Parser
					 * ********************/
					InputStream html = nURL.openStream();
					source = new Source(new InputStreamReader(html, "utf-8"));
					source.fullSequentialParse();

					int tr_count = source.getAllElements(HTMLElementName.TR).size();
					Element tr = null;
					
					HashMap<String, String> hashmap = null;
//					Logg.d(TAG, "tr_count : "+tr_count);
//					int count = 1;
					for(int i=1; i<tr_count; i++) {
						tr = (Element) source.getAllElements(HTMLElementName.TR).get(i);
						int td_count = tr.getAllElements(HTMLElementName.TD).size();
//						Logg.d(TAG, "count : "+ count++);
						String real_date	= "";
						String real_time	= "";
						String stadium      = "";
						String compare_date = ""; //db와 날짜 비교
						String a_team		= "";
						String b_team		= "";
						String score		= "";
							
						hashmap = new HashMap<String, String>();
						String string = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
				/*		if(td_count == 7){  //kbo 아직 시작안한경기
							Log.d(TAG, "KBO2");
								String no_match = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
								if(!no_match.substring(0, 2).equals("경기")){
									String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
									String team = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();	
									String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();
									String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();
									String tv = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
									String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
									String weather = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
									
									real_date = month + "월 " + date.replaceAll(" ", "");
									real_time =time;
									String team1 = team.substring(team.indexOf(">")+1, team.indexOf("</a>"));
									String team2 = team.substring(team.lastIndexOf("'>")+2, team.lastIndexOf("</a>"));
									//String team1 = team.substring(0, team.indexOf(" vs"));
									//String team2 = team.substring(team.indexOf("vs ")+3);
										
									compare_date = mYear+mMonth+date.substring(0, date.lastIndexOf("일 "));
										
									a_team = team1;	
									b_team = team2;	
										
									if(team2.contains("<img src=")==true){
											
										score = "경기 취소";
									}
									//Logg.d(TAG, "date : "+date);
									//Logg.d(TAG, "team1 : "+team1);
									//Logg.d(TAG, "team2 : "+team2);
									
									//Logg.d(TAG, "time : "+time);
									//Logg.d(TAG, "compare_date : "+compare_date);
									//Logg.d(TAG, "relay : "+relay);
									//Logg.d(TAG, "tv : "+tv);
									//Logg.d(TAG, "l_stadium : "+l_stadium);
									//Logg.d(TAG, "weather : "+weather);
										
									hashmap.put("real_date",	real_date);
									hashmap.put("real_time",	real_time.trim());
									hashmap.put("stadium",	    l_stadium);
									hashmap.put("compare_date",	compare_date);
									hashmap.put("a_team",		a_team.trim());
									hashmap.put("b_team",		b_team.trim());
									Baseball baseball = call_alarm_values(compare_date, a_team.trim(), b_team.trim()); 
									if(baseball!=null){
										hashmap.put("enable",		baseball.getEnable());
										int notification = Integer.parseInt(baseball.getNotification());
										hashmap.put("notification",		notification_time_array_name[notification]);
											
									}else{
										hashmap.put("enable",		"false");
										hashmap.put("notification",		notification_time_array_name[0]);
									}								
									hashmap.put("score",		score);
									
								}
									
						}else if(td_count == 9){ //지난 한국 경기 
							Log.d(TAG, "KBO1");
							String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
							String team1 = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();	
							String vs = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();	
							String team2 = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();								
							String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
							String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
							String tv = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
							String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(7)).getContent().toString();
							String weather = ((Element)tr.getAllElements(HTMLElementName.TD).get(8)).getContent().toString();
								
							real_date = month + "월 " + date.replaceAll(" ", "");
							real_time = time;
								
							int team1_open_em_tag = team1.indexOf("<em>");
							int team1_close_em_tag = team1.indexOf("</em>");
							
							int team2_open_em_tag = team2.indexOf("<em>");
							int team2_close_em_tag = team2.indexOf("</em>");
								
							a_team = team1.substring(team1.indexOf("'>")+2, team1.indexOf("</a>"));
							b_team = team2.substring(team2.indexOf("'>")+2,  team2.indexOf("</a>"));
							String a_team_score = "";
							a_team_score = team1.substring(team1_open_em_tag + 4, team1_close_em_tag);
							String b_team_score = "";
							b_team_score = team2.substring(team2_open_em_tag + 4, team2_close_em_tag);
								
							if(team2.contains("<img src=")==true){								
								score = "경기 취소";
							}else{
								score = a_team_score+ ":"+b_team_score;
							}
							hashmap.put("real_date",	real_date);
							hashmap.put("real_time",	real_time.trim());
							hashmap.put("stadium",	    l_stadium);
							hashmap.put("compare_date",	compare_date);
							hashmap.put("a_team",		a_team.trim());
							hashmap.put("b_team",		b_team.trim());
								
							hashmap.put("enable",		"false");
							hashmap.put("notification",		context.getResources().getText(R.string.match_finished).toString()); // 알람 몇시간전 알림 
							hashmap.put("score",		score);
						}else if(td_count == 10){ //해외 야구 종료
							Log.d(TAG, "MLB1");
							String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
							String team1 = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();	
							String vs = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();	
							String team2 = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();								
							String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
							String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
							String tv = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
							String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(7)).getContent().toString();
							String league = ((Element)tr.getAllElements(HTMLElementName.TD).get(8)).getContent().toString();
							String etc = ((Element)tr.getAllElements(HTMLElementName.TD).get(9)).getContent().toString();
								
								
							Logg.d(TAG, "date : "+date);
							Logg.d(TAG, "team1 : "+team1);
							Logg.d(TAG, "team2 : "+team2);
							Logg.d(TAG, "time : "+time);
							
							Logg.d(TAG, "relay : "+relay);
							Logg.d(TAG, "tv : "+tv);
							Logg.d(TAG, "l_stadium : "+l_stadium);
							Logg.d(TAG, "etc : "+etc);
							Logg.d(TAG, "compare_date : "+compare_date);
							real_date = month + "월 " + date.replaceAll(" ", "");
							real_time = time;
							int team1_open_em_tag = team1.indexOf("<em>");
							int team1_close_em_tag = team1.indexOf("</em>");
						
							int team2_open_em_tag = team2.indexOf("<em>");
							int team2_close_em_tag = team2.indexOf("</em>");
							String a_team_score = "";
							a_team_score = team1.substring(team1_open_em_tag + 4, team1_close_em_tag);
							String b_team_score = "";
							b_team_score = team2.substring(team2_open_em_tag + 4, team2_close_em_tag);
							
							a_team = team1.substring(team1.indexOf(">")+1, team1.indexOf("</a>"));
							b_team = team2.substring(team2.lastIndexOf("\">")+2, team2.lastIndexOf("</a>"));
							if(team2.contains("<img src=")==true){								
								score = "경기 취소";
							}else{
								score = a_team_score+ ":"+b_team_score;
							}
							hashmap.put("real_date",	real_date);
							hashmap.put("real_time",	real_time.trim());
							hashmap.put("stadium",	    l_stadium);
							hashmap.put("compare_date",	compare_date);
							hashmap.put("a_team",		a_team.trim());
							hashmap.put("b_team",		b_team.trim());
								
							hashmap.put("enable",		"false");
							hashmap.put("notification",		context.getResources().getText(R.string.match_finished).toString()); // 알람 몇시간전 알림 
							hashmap.put("score",		score);
						}else if(td_count == 8){
							Log.d(TAG, "MLB2");
							String no_match = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();
							if(!no_match.substring(0, 2).equals("경기")){
								String date = ((Element)tr.getAllElements(HTMLElementName.TD).get(0)).getContent().toString();
								String team = ((Element)tr.getAllElements(HTMLElementName.TD).get(1)).getContent().toString();	
								String time = ((Element)tr.getAllElements(HTMLElementName.TD).get(2)).getContent().toString();
								String relay = ((Element)tr.getAllElements(HTMLElementName.TD).get(3)).getContent().toString();
								String tv = ((Element)tr.getAllElements(HTMLElementName.TD).get(4)).getContent().toString();
								String l_stadium = ((Element)tr.getAllElements(HTMLElementName.TD).get(5)).getContent().toString();
								String league = ((Element)tr.getAllElements(HTMLElementName.TD).get(6)).getContent().toString();
								String etc = ((Element)tr.getAllElements(HTMLElementName.TD).get(7)).getContent().toString();
								real_date = month + "월 " + date.replaceAll(" ", "");
								real_time =time;
								String team1 = team.substring(team.indexOf(">")+1, team.indexOf("</a>"));
								String team2 = team.substring(team.lastIndexOf("\">")+2, team.lastIndexOf("</a>"));
								compare_date = mYear+mMonth+date.substring(0, date.lastIndexOf("일 "));
									
								a_team = team1;	
								b_team = team2;	
									
								if(team2.contains("<img src=")==true){									
									score = "경기 취소";
								}
									
								Logg.e(TAG, "date : "+date);
								Logg.e(TAG, "team1 : "+team1);
								Logg.e(TAG, "team2 : "+team2);
								Logg.e(TAG, "time : "+time);
								
								Logg.e(TAG, "relay : "+relay);
								Logg.e(TAG, "tv : "+tv);
								Logg.e(TAG, "l_stadium : "+l_stadium);
								Logg.e(TAG, "etc : "+etc);
								Logg.e(TAG, "compare_date : "+compare_date);
								
								hashmap.put("real_date",	real_date);
								hashmap.put("real_time",	real_time.trim());
								hashmap.put("stadium",	    l_stadium);
								hashmap.put("compare_date",	compare_date);
								hashmap.put("a_team",		a_team.trim());
								hashmap.put("b_team",		b_team.trim());
								Baseball baseball = call_alarm_values(compare_date, a_team.trim(), b_team.trim()); 
								if(baseball!=null){
									hashmap.put("enable",		baseball.getEnable());
									int notification = Integer.parseInt(baseball.getNotification());
									hashmap.put("notification",		notification_time_array_name[notification]);
										
								}else{
									hashmap.put("enable",		"false");
									hashmap.put("notification",		notification_time_array_name[0]);
								}								
								hashmap.put("score",		score);
									
							}
						}*/
							
						data.add(hashmap);
					}
					

					handler.post(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							pDialog.dismiss();
							//Logg.d(TAG, "==끝==");
							handler.sendEmptyMessage(0);
						}
					});
				} catch(MalformedURLException e) {
					e.printStackTrace();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			
		}.start();
	}
	
	private Baseball call_alarm_values(String key_compare_date, String key_a_team, String key_b_team){
		Baseball baseball = null;
    	SQLiteDatabase databse = null;		
		if(databse == null){
			databse = context.openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + " = '" +key_compare_date+"' and "+ DatabaseHelper.DATABASE_COLUMN_A_TEAM +" = '"+key_a_team+"' and "+DatabaseHelper.DATABASE_COLUMN_B_TEAM+" = "+"'"+key_b_team+"'";		
		
		Cursor cursor = null;

		try {
			cursor = databse.rawQuery("SELECT "
					+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ENABLED + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAGUE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_STADIUM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_A_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_B_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SCORE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SMS + ", "
					+ DatabaseHelper.DATABASE_COLUMN_VIDEO + ", "
					+ DatabaseHelper.DATABASE_COLUMN_RECORD + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_HIGHLIGHT + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_POWER + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_EXPLANATION + " " + " FROM "
					+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
			if (cursor != null && cursor.moveToFirst()) {
				do {
					
					baseball = new Baseball(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23));
					
				} while (cursor.moveToNext());
			}		
					
								
		} finally {
			if (cursor != null)
				cursor.close();
			if(databse != null){
				databse.close();
			}
		}
		return baseball;
    }
}
